<template>
  <div class="box">
    <SearchForm
      title="用户列表"
      :formInputs="searchFromInputs"
      :form="searchFrom"
      @clickSubmitForm="loadData"
    >
      <a-button type="default">
        重置
      </a-button>
    </SearchForm>
    <div class="table">
      <a-button icon="plus" type="link" @click="actionClick('add')"
        >新建</a-button
      >
      <a-table
        :columns="columns"
        :data-source="data"
        :rowKey="(record) => record.userName"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <a-space :size="10" slot="operation" slot-scope="text, record">
          <a-popconfirm
            title="确定删除?"
            v-if="record.role !== 'admin'"
            @confirm="() => actionClick('remove', record)"
          >
            <a><a-icon type="delete" /> 删除</a>
          </a-popconfirm>
          <a @click="actionClick('edit', record)"
            ><a-icon type="edit" /> 编辑</a
          >
        </a-space>
      </a-table>
    </div>
    <FormModal
      :formConfig="formModalConfig"
      ref="submitForm"
      @submit="submitForm"
    />
  </div>
</template>

<script>
import SearchForm from "../components/SearchForm";
import FormModal from "../components/FormModal";
import _ from "lodash";

const roles = [
  { label: "管理员", value: "manager" },
  { label: "用户", value: "user" },
];

const columns = [
  { title: "名称", dataIndex: "name", key: "name" },
  { title: "用户名", dataIndex: "userName", key: "userName" },
  {
    title: "角色",
    dataIndex: "role",
    key: "role",
    customRender: (v) => {
      const role = _.find(roles, { value: v });
      return role ? role.label : null;
    },
  },
  { title: "电话", dataIndex: "tel", key: "tel" },
  {
    title: "操作",
    key: "operation",
    align: "center",
    scopedSlots: { customRender: "operation" },
  },
];

const searchFromInputs = [
  {
    model: "name",
    label: "名称",
    type: "input",
  },
  {
    model: "userName",
    label: "用户名",
    type: "input",
  },
  {
    model: "role",
    label: "角色",
    type: "select",
    opts: [
      { label: "不限", value: undefined },
      { label: "管理员", value: "manager" },
      { label: "用户", value: "user" },
    ],
  },
];

// 除初次动态加载roles选项之外，当作常量使用
const formItems = [
  {
    name: "userName",
    label: "用户名",
    type: "input",
    disabled: true,
    rules: [{ required: true, message: `请输入用户名` }],
  },
  {
    name: "name",
    label: "名称",
    type: "input",
    rules: [{ required: true, message: `请输入名称` }],
  },
  {
    name: "role",
    label: "角色",
    type: "select",
    options: roles,
    rules: [{ required: true, message: `请选择角色` }],
  },
  {
    name: "tel",
    label: "电话",
    type: "input",
  },
];

export default {
  data() {
    return {
      searchFrom: {
        name: "",
        userName: "",
        role: undefined,
      },
      searchFromInputs,
      formModalConfig: {
        title: "用户",
        items: formItems,
      },
      action: null,
      data: [],
      columns,
      pagination: {
        pageSize: 10,
        current: 1,
      },
      loading: false,
      confirmPwd: null,
    };
  },
  created() {
    this.loadData();
  },
  methods: {
    handleTableChange(pagination) {
      const pager = { ...this.pagination };
      pager.current = pagination.current;
      this.pagination = pager;
      this.loadData();
    },
    getUser(params = {}) {
      this.loading = true;
      this.$myaxios
        .get(`/user/list`, { params: { ...params } })
        .then((response) => {
          this.loading = false;
          const { success, data, msg } = response.data;
          if (success) {
            const { list, totalCount } = data;
            this.data = list;
            const pagination = { ...this.pagination };
            pagination.total = totalCount;
            this.pagination = pagination;
          } else {
            this.$message.error(msg);
          }
        });
    },
    loadData() {
      this.getUser({
        ...this.searchFrom,
        size: this.pagination.pageSize,
        page: this.pagination.current,
      });
    },
    actionClick(action, item = {}) {
      const formUserName = _.find(this.formModalConfig.items, {
        name: "userName",
      });
      if (action === "add") {
        // 添加时用户名输入框启用
        formUserName.disabled = false;
        // 添加时提交表单中需要password和password_confirmation
        this.formModalConfig.items = [
          ...formItems,
          {
            name: "pwd",
            label: "密码",
            type: "password",
            rules: [
              { required: true, message: `请输入密码` },
              { min: 6, message: "密码至少6位" },
              {
                validator: this.handlePass,
              },
            ],
          },
          {
            name: "pwd_confirmation",
            label: "确认密码",
            type: "password",
            rules: [
              { required: true, message: `请输入确认密码` },
              {
                validator: this.handleConfirmPass,
              },
            ],
          },
        ];

        this.$refs.submitForm.handleOpenForm();
      } else if (action === "edit") {
        // 修改时用户名输入框禁用
        formUserName.disabled = true;
        // 修改时提交表单中不需要password和password_confirmation
        this.formModalConfig.items = [...formItems];

        this.$refs.submitForm.handleOpenForm(item);
      } else if (action === "remove") {
        this.$myaxios
          .delete("/user", { params: { userName: item.userName } })
          .then((res) => {
            const result = res.data;
            if (result) {
              const { success, msg } = result;
              if (success) {
                this.$message.success("删除成功");
                this.loadData();
              } else {
                this.$message.error(msg);
              }
            }
          });
      }
      this.action = action;
    },
    submitForm(values) {
      let url = null;
      let method;
      if (this.action === "edit") {
        url = "/user?userName=" + values.userName;
        method = "PUT";
      } else if (this.action === "add") {
        url = "/user";
        method = "POST";
      }
      if (url) {
        this.$myaxios({
          method,
          url: url,
          data: values,
        }).then((res) => {
          const result = res.data;
          if (result) {
            const { success, msg } = result;
            if (success) {
              this.$refs.submitForm.visible = false;
              this.$message.success("用户信息提交成功");
              this.loadData();
            } else {
              this.$message.error(msg);
            }
          }
        });
      }
    },
    handlePass(rule, value, callback) {
      const form = this.$refs.submitForm.form;
      // 密码更新且确认密码有值，触发确认密码的校验
      if (value && this.confirmPwd) {
        form.validateFields(["pwd_confirmation"], {
          force: true,
        });
      }
      callback();
    },
    handleConfirmPass(rule, value, callback) {
      const form = this.$refs.submitForm.form;
      // 确认密码有值,那么则与表单中密码做匹配
      if (value && value !== form.getFieldValue("pwd")) {
        callback("确认密码错误！");
      } else {
        callback();
      }
      // 记录确认密码
      this.confirmPwd = value;
    },
  },
  components: {
    SearchForm,
    FormModal,
  },
};
</script>

<style lang="less" scoped>
.box {
  height: 100%;
  display: flex;
  flex-direction: column;

  .table {
    flex: 1;
    background-color: white;
    padding: 10px 10px 0 10px;
    text-align: right;
  }
}
</style>
